/*global cordova, StatusBar, angular, window */
(function(angular) {
    'use strict';
    var app = angular.module('myApp', []);

    app.controller('MainCtrl', ['$scope', '$http', '$timeout', function($scope, $http, $timeout){
		console.log('MainCtrl IN');

		$scope.allUserList = [];
		$scope.isShowAddContent = false;
		$scope.isValidator = false;

		$scope.eidModel = '';
		$scope.nameModel = '';
		$scope.genderModel = '';
		$scope.ageModel = '';
		$scope.emailModel = '';
		$scope.phoneModel = '';
		$scope.addressModel = '';

		$scope.init = function () {
			$scope.doValidator('id_add_info');
			$scope.doValidator('id_edit_info');

			$scope.initDefault();
			$scope.getAllUser();
		};

		$scope.doValidator = function (id) {
			$('#' + id).bootstrapValidator({
				// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
				feedbackIcons: {
					valid: 'glyphicon glyphicon-ok',
					invalid: 'glyphicon glyphicon-remove',
					validating: 'glyphicon glyphicon-refresh'
				},
				fields: {
					eid: {
						validators: {
							notEmpty: {
								message: 'Please supply your eid'
							}
						}
					},
					name: {
						validators: {
							notEmpty: {
								message: 'Please supply your name'
							}
						}
					},
					age: {
						validators: {
							notEmpty: {
								message: 'Please supply your age'
							},
							stringLength: {
								min: 1,
								max: 3,
								message: 'Please supply a valid length number'
							},
							regexp: {
								regexp: /^[1-9]+$/,
								message: 'Please supply a number'
							},
						}
					},
					email: {
						validators: {
							notEmpty: {
								message: 'Please supply your email address'
							},
							emailAddress: {
								message: 'Please supply a valid email address'
							}
						}
					},
					phone: {
						validators: {
							notEmpty: {
								message: 'Please supply your phone number'
							},
							phone: {
								country: 'CN',
								message: 'Please supply a vaild phone number with area code'
							}
						}
					},
					address: {
						validators: {
							notEmpty: {
								message: 'Please supply your street address'
							}
						}
					}
				}
			});
		};

		$scope.resetForm = function(id) {
            $("#" + id).data('bootstrapValidator').resetForm();
		};

		$scope.initDefault = function (params) {
			if (params) {
				$scope.eidModel = params.eid;
				$scope.nameModel = params.name;
				$scope.genderModel = params.gender;
				$scope.ageModel = params.age;
				$scope.emailModel = params.email;
				$scope.phoneModel = params.phone;
				$scope.addressModel = params.address;
				// $scope.resetForm('id_edit_info');
			} else {
				$scope.eidModel = '';
				$scope.nameModel = '';
				$scope.genderModel = 'male';
				$scope.ageModel = '';
				$scope.emailModel = '';
				$scope.phoneModel = '';
				$scope.addressModel = '';
				$scope.resetForm('id_add_info');
			}
		};

		$scope.getAllUser = function() {
			console.log('getAllUser()');

            $http.get("/api/v1/user/getAll", {}).success(function (data) {
                console.log('get all user success. data: ' + data);

                $scope.allUserList = data;
            }).error(function (error) {
                console.log('get all user failed. error: ' + error);
            });
		};

		$scope.onClickAddSubmit = function() {
			console.log('onClickAddSubmit()');

			let isValid = $('#id_add_info').data('bootstrapValidator').validate().isValid();
			if (isValid) {
				let params = {
					eid: $scope.eidModel,
					name: $scope.nameModel,
					gender: $scope.genderModel,
					age: $scope.ageModel,
					email: $scope.emailModel,
					phone: $scope.phoneModel,
					address: $scope.addressModel
				};

				let url = '/api/v1/user/add';
				$http.post(url, params, {}).success((data) => {
					console.log(`add user success. data: ${data}`);

					// reset form input field
					$scope.resetForm('id_add_info');

					$scope.getAllUser();
				}).error((error) => {
					console.log(`add user failed. error: ${error}`);
				}).finally(() => {
					$scope.initDefault();
				});
			} else {
				$('#id_add_info').data('bootstrapValidator').disableSubmitButtons(true);
			}
		};

		$scope.onClickEditSubmit = function() {
			console.log('onClickEditSubmit()');

			let isValid = $('#id_edit_info').data('bootstrapValidator').validate().isValid();
			if (isValid) {
				let params = {
					eid: $scope.eidModel,
					name: $scope.nameModel,
					gender: $scope.genderModel,
					age: $scope.ageModel,
					email: $scope.emailModel,
					phone: $scope.phoneModel,
					address: $scope.addressModel
				};

				let url = '/api/v1/user/update';
				$http.post(url, params, {}).success((data) => {
					console.log(`eidt user success. data: ${data}`);


					// reset form input field
					$scope.resetForm('id_edit_info');

					$scope.getAllUser();
				}).error((error) => {
					console.log(`eidt user failed. error: ${error}`);
				}).finally(() => {
					$scope.initDefault();
				});
			} else {
				$('#id_edit_info').data('bootstrapValidator').disableSubmitButtons(true);
			}
		};

		$scope.onClickAdd = function() {
			console.log('onClickAdd() ');

			$scope.isShowAddContent = !$scope.isShowAddContent;
			$scope.initDefault();
		};

		$scope.onClickEdit = function(item) {
			console.log('onClickEdit() params: ' + JSON.stringify(item));

			$scope.isShowAddContent = false;
			$scope.initDefault(item);
		};

		$scope.onClickEditCancel = function () {
			$scope.initDefault();
			$("#id_edit_info").data('bootstrapValidator').resetForm();
		};

		$scope.onClickDelete = function(item) {
			console.log('onClickDelete() params: ' + JSON.stringify(item));

			var confirmMsg = window.confirm('do you want to delete the use?');
			if (confirmMsg) {
				let url = `/api/v1/user/delete?eid=${item.eid}`;
				$http.get(url, {}).success(function (data) {
					console.log('delete user success. data: ' + data);

					$scope.getAllUser();
				}).error(function (error) {
					console.log('delete user failed. error: ' + error);
				});
			} else {
				console.log('you canceled the delete option');
			}

		};

		$scope.generateEID = function() {
			$scope.eidModel = Date.now();

			$timeout(function() {
				$('#id_add_info').data('bootstrapValidator').revalidateField('eid');
			});
		};

		$timeout($scope.init);
    }]);


})(angular);